package library.and.xps.com.step.view.fragment;


import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import io.realm.RealmResults;
import library.and.xps.com.step.R;
import library.and.xps.com.step.util.StepGenerator;
import library.and.xps.com.step.util.StepManager;
import library.and.xps.com.step.m.model.DaliyRecord;
import library.and.xps.com.step.m.model.WeeklyRecord;
import library.and.xps.com.step.chatFormatter.DayAxisValueFormatter;
import library.and.xps.com.step.chatFormatter.IndexAxisValueFormatter;
import library.and.xps.com.step.chatFormatter.MyAxisValueFormatter;
import library.and.xps.com.step.util.CommonUtils;

public class HistoryFragment extends Fragment implements OnChartValueSelectedListener {
    View view;
    BarChart barChart;
    ArrayList<DaliyRecord> records;

    TextView tv_lable_setpCount, tv_lable_milesCount;
    TextView tv_setpCount, tv_milesCount;
    StatisticsType currentStatisticsType = StatisticsType.Daily;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_daily, container, false);
        barChart = (BarChart) view.findViewById(R.id.barChat);
        barChart.setDrawBarShadow(false);
        barChart.setDrawGridBackground(false);
        barChart.getDescription().setEnabled(false);
        barChart.setNoDataText("还没有运动数据");

        RealmResults<DaliyRecord> re = StepGenerator.getInstance().getRecordAll();

        if (re.size() == 0) {//当没有数据时 直接返回view
            return view;
        } else if (re.size() < 7) {//当记录小于7条时 补全到7条
            records = StepGenerator.getInstance().DayRecordSupplement(re);
        } else {
            records = StepGenerator.getInstance().RToA(re);
        }

        IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(barChart, records);
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(7);
        xAxis.setAxisLineColor(Color.WHITE);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setValueFormatter(xAxisFormatter);

        barChart.setPinchZoom(false);
        barChart.setDoubleTapToZoomEnabled(false);
        barChart.setOnChartValueSelectedListener(this);
        barChart.setScaleEnabled(false);
        barChart.setAutoScaleMinMaxEnabled(true);
        barChart.getLegend().setEnabled(false);
        barChart.moveViewTo(records.size(), 1f, YAxis.AxisDependency.RIGHT);
        barChart.notifyDataSetChanged();

        IAxisValueFormatter custom = new MyAxisValueFormatter();
        YAxis leftAxis = barChart.getAxisLeft();  // 左刻度
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(0);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setEnabled(false);

        YAxis rightAxis = barChart.getAxisRight();//右刻度
        rightAxis.setDrawGridLines(false);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(0);
        rightAxis.setAxisMinimum(0f);
        rightAxis.setEnabled(false);

        initView();
        initDaily();
        return view;
    }

    void initView() {
        tv_lable_setpCount = (TextView) view.findViewById(R.id.tv_lable_setpCount);
        tv_lable_milesCount = (TextView) view.findViewById(R.id.tv_lable__milesCount);

        tv_setpCount = (TextView) view.findViewById(R.id.tv_setpCount);
        tv_milesCount = (TextView) view.findViewById(R.id.tv_milesCount);
    }

    private void initDaily() {
        if (records == null) return;

        ArrayList<BarEntry> yVals1 = new ArrayList<>();
        //设置图表下部lable
        IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(barChart, records);
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(7);
        xAxis.setAxisLineColor(Color.WHITE);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setValueFormatter(xAxisFormatter);

        for (int i = 0; i < records.size(); i++) {
            BarEntry barChart = new BarEntry(i, records.get(i).getStepCount(), records.get(i));
            yVals1.add(barChart);
        }

        BarDataSet set1;
        if (barChart.getData() != null &&
                barChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) barChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "");
            set1.setDrawIcons(false);
            set1.setColors(Color.parseColor("#72ffffff"));
            set1.setHighLightColor(Color.WHITE);
            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setDrawValues(false);
            data.setBarWidth(0.95f);
            barChart.setData(data);
        }
        barChart.setVisibleXRangeMaximum(10);
        barChart.animateY(600);

        resetLableDaily();
        currentStatisticsType = StatisticsType.Daily;
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        EventBus.getDefault().post(e);

        Object o = e.getData();
        if (o instanceof DaliyRecord) {
            DaliyRecord daliyRecord = (DaliyRecord) o;
            tv_setpCount.setText(daliyRecord.getStepCount() + "");
            tv_milesCount.setText(CommonUtils.stepToMiles(daliyRecord.getStepCount()) + "");
        } else if (o instanceof WeeklyRecord) {
            WeeklyRecord weekRecord = (WeeklyRecord) o;
            tv_setpCount.setText(weekRecord.getStepsAverage() + "");
            tv_milesCount.setText(weekRecord.getMilesCount() + "");
        }

    }

    @Override
    public void onNothingSelected() {

    }

    public void toogleWeekly() {
        ArrayList<BarEntry> yVals1 = new ArrayList<>();
        BarDataSet set1;

        ArrayList<WeeklyRecord> recordWeekly = StepGenerator.getInstance().getWeeklyRecord();

        if (recordWeekly.size() < 7) {
            recordWeekly = StepManager.getInstance().WeekRecordSupplement(recordWeekly);
        }

        for (int i = 0; i < recordWeekly.size(); i++) {
            WeeklyRecord weeklyRecord = recordWeekly.get(i);
            BarEntry barChart = new BarEntry(i, weeklyRecord.getStepsAverage(), weeklyRecord);
            yVals1.add(barChart);
        }

        String[] strings = getLables(recordWeekly);

        IndexAxisValueFormatter xAxisFormatter = new IndexAxisValueFormatter(strings);
        XAxis xAxis = barChart.getXAxis();
        xAxis.setValueFormatter(xAxisFormatter);

        barChart.moveViewTo(1, 1f, YAxis.AxisDependency.RIGHT);
        set1 = (BarDataSet) barChart.getData().getDataSetByIndex(0);
        set1.setValues(yVals1);
        barChart.setVisibleXRangeMaximum(10);
        barChart.animateY(600);

        resetLableWeek();
        currentStatisticsType = StatisticsType.Weekly;
    }

    public void toogleDaily() {
        initDaily();
    }

    public void toogleMonthly() {

    }

    /**
     * @param records 周记录
     * @return string列表 单位为这一周记录的开始日期和结束日期
     * sample: String[] lables = {"4/19-4/23","4/24-4/30",...};
     */
    public String[] getLables(ArrayList<WeeklyRecord> records) {
        ArrayList<String> lables = new ArrayList<>();
        for (WeeklyRecord record : records) {
            lables.add(record.getSimpleDateSpanDes());
        }

        String[] lablesStr = new String[lables.size()];
        for (int i = 0; i < lables.size(); i++) {
            lablesStr[i] = lables.get(i);
        }

        return lablesStr;
    }

    void resetLableDaily() {
        tv_lable_setpCount.setText("步数");
        tv_lable_milesCount.setText("公里数");

        BarDataSet set1 = (BarDataSet) barChart.getBarData().getDataSets().get(0);
        hightLightChart(set1);

    }

    void resetLableWeek() {
        tv_lable_setpCount.setText("日均步数");
        tv_lable_milesCount.setText("总公里数");

        //第一个Week的记录
        BarDataSet set1 = (BarDataSet) barChart.getBarData().getDataSets().get(0);
        BarEntry barEntry = set1.getEntryForIndex(0);
        WeeklyRecord weeklyRecord = (WeeklyRecord) barEntry.getData();

        //highlight第一个dataset的第一个记录
        barChart.highlightValue(0, 0);

        tv_setpCount.setText(weeklyRecord.getStepsAverage() + "");
        tv_milesCount.setText(weeklyRecord.getMilesCount() + "");
    }

    enum StatisticsType {
        Daily, Weekly, Monthly
    }

    //高亮一条数据
    void hightLightChart(BarDataSet set1) {
        //因为不足7天的时候添加了几条空数据 所以设置高亮时 从后往前遍历
        //并且初始化两个TextView的数据
        for (int i = set1.getEntryCount() - 1; i >= 0; i--) {
            BarEntry d = set1.getEntryForIndex(i);
            DaliyRecord daliyRecord = (DaliyRecord) d.getData();
            if (daliyRecord.getStepCount() > 0) {

                tv_setpCount.setText(daliyRecord.getStepCount() + "");
                tv_milesCount.setText(CommonUtils.stepToMiles(daliyRecord.getStepCount()) + "");

                barChart.highlightValue(i, 0);
                break;
            }
        }
    }

}
